package top.heue.utils.base.helper

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter

class FragmentPagerAdapterHelper : FragmentStateAdapter {
    private var manager: FragmentManager
    private var fragments: MutableList<Class<out Fragment>> = mutableListOf()

    constructor(
        activity: FragmentActivity,
        fragmentClass: MutableList<Class<out Fragment>>? = null
    ) : super(activity) {
        manager = activity.supportFragmentManager
        fragmentClass?.let { fragments = it }
    }

    constructor(
        fragment: Fragment,
        fragmentClass: MutableList<Class<out Fragment>>? = null
    ) : super(fragment) {
        manager = fragment.childFragmentManager
        fragmentClass?.let { fragments = it }
    }

    constructor(
        fragmentManager: FragmentManager,
        lifecycle: Lifecycle,
        fragmentClass: MutableList<Class<out Fragment>>? = null
    ) : super(fragmentManager, lifecycle) {
        manager = fragmentManager
        fragmentClass?.let { fragments = it }
    }

    override fun getItemCount(): Int = fragments.size

    override fun createFragment(position: Int): Fragment =
        fragments[position].getDeclaredConstructor().newInstance()

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    /** 通过序号获取fragment*/
    fun getItem(position: Int): Fragment? =
        manager.findFragmentById(getItemId(position).toInt())

    /** 添加一个fragment，返回序号数字 */
    fun addItem(fragmentClass: Class<out Fragment>): Int {
        fragments.add(fragmentClass)
        val s = fragments.size - 1
        notifyItemInserted(s)
        return s
    }

    /** 移除一个fragment*/
    fun removeItem(fragmentClass: Class<out Fragment>) {
        removeItem(fragments.indexOf(fragmentClass))
    }

    /** 移除一个fragment*/
    fun removeItem(position: Int) {
        fragments.removeAt(position)
        notifyItemRemoved(position)
    }
}